#!/usr/bin/python

# to calculate the s/b for different cuts

import sys
import os
import glob
from math import sqrt,pow

cutset=["NOM", "SET1", "SET2", "SET3", "SET4", "SET12", "SET13", "SET14", "SET23", "SET24", "SET34", "SET123", "SET124", "SET134", "SET234", "SET1234"]

ch=["ee", "mm", "em", "incl"]


for chn in ch:	
	# output file
	output="sig_allSets_"+chn+".txt"
	try: fout=open(output, "w")
	except IOError:
		print "Error => %s can not be opend" % output
		sys.exit(1)

	dict_sb={}

	for set in cutset:
		# input file, from the 16 sets folder, eg NOM/NOM_ee_total_results_ee
		log=set+"/"+set+"_total_results_"+chn
		try: fin=open(log, "r")
		except IOError:
			print "Error => %s can not be read" % log
			sys.exit(1)
		
		s,b=-1,-1
		for line in fin.readlines():
			if line[-1]=="\n": line=line[:-1]
			sline=line.split()
			if len(sline) != 11: continue
			cut=sline[0]
			# only look at dEtajj stage
			if cut == "dEtajj": 
				s,b=sline[2],sline[8]
				s,b=float(s),float(b)
				# significance      
				if b != 0: sig=s/sqrt(b)
				else: 	   sig=-1

		fin.close()
		if s==-1 or b==-1: continue
		if not dict_sb.has_key(set): dict_sb[set]={}
		dict_sb[set]["S"]=float(s)
		dict_sb[set]["B"]=float(b)
		dict_sb[set]["Sig"]=float(sig)
		
	# write into file
	fout.write("%-14s" % "set")
	for set in cutset:
		fout.write("%-14s" % set)
	fout.write("\n")
	fout.write("%-14s" % "S")
	for set in cutset:
		fout.write("%-14.7e" % dict_sb[set]["S"])
	fout.write("\n")
	fout.write("%-14s" % "B")
	for set in cutset:
		fout.write("%-14.7e" % dict_sb[set]["B"])
	fout.write("\n")
	fout.write("%-14s" % "Sig")
	for set in cutset:
		fout.write("%-14.7e" % dict_sb[set]["Sig"])
	fout.close()
	
		 
